<?php
$username=trim($_POST['username']);
$pw=trim($_POST['pw']);
$cpw=trim($_POST['cpw']);
$sex=$_POST['sex'];
$email=trim($_POST['email']);
$fav=@implode(",",$_POST['fav']);
include_once "conn.php";
/*
echo "您输入的用户名为: ".$username;
echo "<br/>";
echo "您输入的密码是: ".$pw;
echo "<br/>";
echo "您输入的性别是: ";
echo $sex==1?'男':'女';
echo "<br/>";
echo "您输入的爱好是: ";
$fav=implode(",",$fav);
echo $fav;
*/


//进行验证
if (!strlen($username)||!strlen($pw)){
    echo "<script>alert('用户名和密码都必须要填写');history.back();</script>";
    exit;
}
else{
    if (!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
        echo "<script>alert('用户名由大小写字母和数字构成,长度为3-10个字符!');history.back();</script>";
        exit;
    }
}
//判断两次密码是否相等
if ($pw<>$cpw){
    echo "<script>alert('两次密码须保持一致');history.back();</script>";
    exit;
}
else{
    if (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pw)){
        echo "<script>alert('密码由大小写字母、数字和_以及*构成,长度为6-10个字符!');history.back();</script>";
        exit;
    }
}
if (!empty($email)){
    if (!preg_match('/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/',$email)){
        echo "<script>alert('邮箱格式不正确');history.back();</script>";
        exit;
    }
}
//判断用户名是否重复
$sql="select * from info where username = '$username'";
$result=mysqli_query($conn,$sql);  //返回一个记录集
$num=mysqli_num_rows($result);
if ($num){
    echo "<script>alert('此用户名已被占用,请重新输入');history.back();</script>";
    exit;
}
//sql语句
$sql="insert into info(username,pw,sex,email,fav,createTime) value ('$username','".md5($pw)."','$sex','$email','$fav','".time()."')";
//$sql="insert into info(username, pw, email, sex, fav, createTime) VALUES ()";  添加数据源后简化的注册语句
$result=mysqli_query($conn,$sql);
if ($result){
    echo "<script>alert('数据库插入成功');location.href='index.php';</script>";
}else{
    echo "<script>alert('数据库插入失败');history.back();</script>";
}




